package com.fee1in;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author linhui
 */
public class XMLConfigBuilder {

    boolean parsed;
    Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration parse(InputStream is) throws DocumentException {

        if (parsed) {
            throw new RuntimeException("Each XMLConfigBuilder can only be used once.");
        }

        parsed = true;
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(is);
        parseConfiguration(document);
        return configuration;
    }

    private void parseConfiguration(Document document) {
        propertiesElement(document.selectSingleNode("//properties"));
        environmentsElement(document.selectSingleNode("//environments"));
        mapperElement(document.selectSingleNode("//mappers"));
    }


    private void propertiesElement(Node properties) {
        List<Element> list = properties.selectNodes("//property");
        Properties variables = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            variables.setProperty(name, value);
        }
        configuration.setVariables(variables);
    }

    private void environmentsElement(Node selectSingleNode) {
        configuration.setDataSource(new PooledDataSource(configuration.variables));
    }

    private  void mapperElement(Node mappers){
        List<Element> list = mappers.selectNodes("//mapper");
        for (Element element : list) {
            String resource = element.attributeValue("resource");
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration,resource);
            xmlMapperBuilder.parse();
        }

    }
}
